#!/usr/bin/python3
"""
Write nginx configuration
"""

import os
import sys

import osbuild.api
from osbuild.util.path import in_tree

SCHEMA_2 = r"""
"options": {
  "additionalProperties": false,
  "properties": {
    "path": {
      "type": "string",
      "description": "Config file location",
      "default": "/etc/nginx/nginx.conf",
      "pattern": "^\\/(?!\\.\\.)((?!\\/\\.\\.\\/).)+$"
    },
    "config": {
      "type": "object",
      "properties": {
        "listen": {
          "type": "string",
          "description": "The address and/or port on which the server will accept requests",
          "default": "*:80"
        },
        "root": {
          "type": "string",
          "description": "The root directory for requests",
          "default": "/usr/share/nginx/html"
        },
        "pid": {
          "type": "string",
          "description": "File that will store the process ID of the main process",
          "default": "/run/nginx.pid"
        },
        "daemon": {
          "type": "boolean",
          "description": "Whether nginx should become a daemon",
          "default": true
        }
      }
    }
  }
}
"""

def main(tree, options):
    path = options.get("path", "etc/nginx/nginx.conf").lstrip("/")

    config = options.get("config", {})
    listen = config.get("listen", "*:80")
    pid = config.get("pid", "/run/nginx.pid")
    if config.get("daemon", True):
        daemon = "on"
    else:
        daemon = "off"
    root = config.get("root", "/usr/share/nginx/html")

    target = os.path.join(tree, path)
    if not in_tree(target, tree, must_exist=False):
        raise ValueError(f"config file path {target} not in tree")

    content = f"""events {{}}
http {{
  server {{
    listen {listen};
    root {root};
  }}
}}

pid {pid};
daemon {daemon};
"""

    with open(target, "w") as f:
        f.write(content)

    return 0


if __name__ == "__main__":
    args = osbuild.api.arguments()
    sys.exit(main(args["tree"], args["options"]))
